package config

import (
	"log"
	"main/global"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 初始化数据库
func InitDB() {
	user := AppConfig.Database.User
	pass := AppConfig.Database.Password
	dbname := AppConfig.Database.Name
	dsn := user + ":" + pass + "@tcp(127.0.0.1:3306)/" + dbname + "?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("Gorm Open Error: %v", err)
	} else {
		log.Println("Gorm Open Success!")
	}
	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(AppConfig.Database.MaxIdleConns)
	sqlDB.SetMaxOpenConns(AppConfig.Database.MaxOpenConns)
	if err != nil {
		log.Fatalf("Gorm Config Database Error: %v", err)
	} else {
		log.Println("Gorm Config Database Success")
	}
	// 设置db为全局变量
	global.Db = db

}
